package com.twotwoshop.service.order.service.Impl;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.twotwoshop.commom.order.OrderStatus;
import com.twotwoshop.commom.rabbitmq.RabbitConstants;
import com.twotwoshop.commom.redis.RedisConstants;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.goods.dtos.ProductDto;
import com.twotwoshop.domin.goods.pojo.Product;
import com.twotwoshop.domin.order.dtos.OrderDto;
import com.twotwoshop.domin.order.dtos.OrderFindDto;
import com.twotwoshop.domin.order.pojo.Order;
import com.twotwoshop.domin.order.pojo.OrderDetail;
import com.twotwoshop.domin.order.vos.OrderVo;
import com.twotwoshop.domin.user.pojos.ApUser;
import com.twotwoshop.fegin.api.goods.IGoodsClient;
import com.twotwoshop.fegin.api.user.IUserClient;

import com.twotwoshop.service.order.mapper.OrderDetailMapper;
import com.twotwoshop.service.order.mapper.OrderMapper;
import com.twotwoshop.service.order.util.RedisTimeWorker;
import com.twotwoshop.util.thread.AppThreadLocalUtil;


import io.seata.spring.annotation.GlobalTransactional;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.twotwoshop.service.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.twotwoshop.commom.goods.ProductConstants.STATUS_UP;


@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {



    private final IUserClient userClient;

    private final IGoodsClient goodsClient;

    private final RedisTimeWorker redisTimeWorker;

    private final IGoodsClient orderClient;

    private final RabbitTemplate rabbitTemplate;

    private final OrderMapper orderMapper;

    private final OrderDetailMapper orderDetailMapper;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;



    /**
     * 生成下单令牌
     */
    @Override
    public ResponseResult generateOrderToken() {
        // 获取当前用户ID
        Integer userId = AppThreadLocalUtil.getUser().getId();
        // 生成令牌
        String token = UUID.randomUUID().toString();
        // 存入Redis，设置30分钟过期
        String key = RedisConstants.ORDER_TOKEN_KEY + userId + ":" + token;
        stringRedisTemplate.opsForValue().set(key, "1", 30, TimeUnit.MINUTES);
        return ResponseResult.okResult(token);
    }

    /**
     * 校验并删除令牌
     */
    private void checkAndRemoveToken(String token) {
        Integer userId = AppThreadLocalUtil.getUser().getId();
        String key = RedisConstants.ORDER_TOKEN_KEY + userId + ":" + token;

        // 使用Redis的原子操作验证并删除令牌
        Boolean deleted = stringRedisTemplate.delete(key);
        if (Boolean.FALSE.equals(deleted)) {
            throw new RuntimeException("重复提交或令牌已过期");
        }
    }


    /**
     * 下单
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional
    public ResponseResult downOrder(OrderDto orderDto) {


        // 1. 幂等性校验
        try {
            checkAndRemoveToken(orderDto.getIdempotentToken());
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, e.getMessage());
        }

        // 2. 获取用户锁
        RLock redisLock = redissonClient.getLock(RedisConstants.ORDER_LOCK_KEY + AppThreadLocalUtil.getUser().getId());
        try {
            boolean isLock = redisLock.tryLock(5, 10, TimeUnit.SECONDS);
            if (!isLock) {
                return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_INVALID, "订单服务繁忙");
            }

        log.info("开始创建订单，用户：{}, 商品：{}", AppThreadLocalUtil.getUser().getId(), orderDto.getGoodsId());
        
        // 1. 参数校验
        if (orderDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"下单参数为空");
        }
        
        if (orderDto.getTotalFee() == null || orderDto.getTotalFee() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单金额不合法");
        }

  /*      // 2. 获取用户锁，防止用户并发下单
        RLock redisLock = redissonClient.getLock(RedisConstants.ORDER_LOCK_KEY + AppThreadLocalUtil.getUser().getId());
        if (!redisLock.tryLock()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_INVALID,"订单服务繁忙，请稍后再试");
        }

        try {*/
            // 3. 查询商品信息并校验
            ResponseResult responseResult = goodsClient.ProductById(orderDto.getGoodsId());
            if (responseResult.getCode() != 200) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"商品信息获取失败");
            }
            
            Product product = JSONUtil.toBean(JSONUtil.toJsonStr(responseResult.getData()), Product.class);
            if (product.getStatus() != STATUS_UP) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "商品已下架");
            }
            
       /*     // 4. 校验订单金额
            if (!orderDto.getTotalFee().equals(BigDecimal.valueOf(product.getPrice()))) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单金额与商品价格不符");
            }
*/
            // 5. 检查是否重复购买
            Integer userId = AppThreadLocalUtil.getUser().getId();
            if (checkDuplicateOrder(userId, orderDto.getGoodsId())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"您已经购买过该商品");
            }

            // 6. 生成订单号
            long orderId = redisTimeWorker.nextID("order");
            // 检查订单号是否重复
            if (orderMapper.selectById(orderId) != null) {
                log.error("订单号重复，重新生成订单号");
                orderId = redisTimeWorker.nextID("order");
            }
            log.info("生成订单号：{}", orderId);

            // 7. 创建订单对象
            Order order = createOrder(orderId, orderDto, userId, product);
            
            // 8. 保存订单
            if (orderMapper.insert(order) <= 0) {
                throw new RuntimeException("订单保存失败");
            }

            // 9. 更新商品状态
            updateProductStatus(product, orderDto.getSellerId());

            // 10. 创建订单详情
            createOrderDetail(order, product, orderDto.getRemark());



            log.info("订单创建成功，订单号：{}", orderId);


            //生成订单后延迟消息
            // 异步发送消息统计该用户总消费  生成订单
            // 如果 30分钟后用户未支付 取消订单                                                               //延迟时间
            rabbitTemplate.convertAndSend(RabbitConstants.TWOTWO_DLX_ORDER_EXCHANGE,"delay",order,new MessagePostProcessor() {

                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    //添加延迟消息属性
                    message.getMessageProperties().setDelay(500);
                    return message;
                }
            });


            return ResponseResult.okResult(StringUtil.toString(orderId));

        } catch (Exception e) {
            log.error("创建订单失败", e);
            throw new RuntimeException("订单创建失败");
        } finally {
            if (redisLock.isHeldByCurrentThread()) {
                redisLock.unlock();
            }
        }
    }

    // 检查重复购买
    private boolean checkDuplicateOrder(Integer userId, Long goodsId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getGoodsId, goodsId)
                .eq(Order::getSenderId, userId)
                .ne(Order::getStatus, OrderStatus.CANCELLED_CLOSED);
        return orderMapper.selectOne(queryWrapper) != null;
    }

    // 创建订单对象
    private Order createOrder(long orderId, OrderDto orderDto, Integer userId, Product product) {
        Order order = new Order();
        order.setId(orderId);
        order.setPaymentType(orderDto.getPaymentType());
        order.setStatus(OrderStatus.UNPAID);
        order.setTotalFee(orderDto.getTotalFee());
        order.setGoodsId(orderDto.getGoodsId());
        order.setSenderId(Long.valueOf(userId));
        order.setReceiverId(orderDto.getSellerId());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        return order;
    }

    // 更新商品状态
    private void updateProductStatus(Product product, Long sellerId) {
        ProductDto productDto = new ProductDto();
        productDto.setId(product.getId());
        productDto.setStatus(0);
        productDto.setUserId(sellerId);
        
        ResponseResult response = goodsClient.updateStatus(productDto);
        if (response.getCode() != 200) {
            throw new RuntimeException("商品状态更新失败");
        }
    }

    // 创建订单详情
    public void createOrderDetail(Order order, Product product, String remark) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setGoodsId(product.getId());
        orderDetail.setOrderId(order.getId());
        orderDetail.setNum(1);
        orderDetail.setImage(product.getImages());
        orderDetail.setName(product.getTitle());
        orderDetail.setRemark(remark);
        orderDetail.setPrice(product.getPrice());
        orderDetail.setCreateTime(LocalDateTime.now());
        orderDetail.setUpdateTime(LocalDateTime.now());


        
        orderDetailMapper.insert(orderDetail);
    }


    /**
     * 获取订单列表
     *
     * @return
     */
    @Override
    public ResponseResult getOrderList(OrderFindDto orderFindDto) {


        //1.获取当前用户
        Integer userId = AppThreadLocalUtil.getUser().getId();

        LambdaQueryWrapper <Order>queryWrapper = new LambdaQueryWrapper<Order>();
        queryWrapper.eq(Order::getSenderId, userId)
                .orderByDesc(Order::getCreateTime);
        ;

        if (orderFindDto.getStatus()!=null){
            queryWrapper.eq(Order::getStatus,orderFindDto.getStatus());
        }


        //2.查询该用户订单信息
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if (orders==null || orders.size()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"暂无订单");
        }





        //最终返回结果

/*        @ApiModelProperty(value = "订单id")
        @TableId(value = "id", type = IdType.INPUT)
        private Long id;

        @ApiModelProperty(value = "总金额，单位为分")
        private Double totalFee;

        @ApiModelProperty(value = "支付类型，1、面交，2、邮寄")
        private Integer paymentType;

        private Long senderId;      // 发送者ID  商家id #

        private Long receiverId;    // 接收者ID  #

        @ApiModelProperty(value = "订单的状态，1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束，已评价")
        private Integer status;*/
        List<OrderVo> orderVos = BeanUtil.copyToList(orders, OrderVo.class);




        for (OrderVo orderVo : orderVos) {

            //设置用户信息

            //查询发布商品人的昵称和头像
            ResponseResult userInfo = userClient.getUserInfoById(orderVo.getSenderId());
            if (userInfo.getCode()==200){
                //拿取用户信息
                String jsonString = JSONUtil.toJsonStr(userInfo.getData());
                ApUser user = JSONUtil.toBean(jsonString, ApUser.class);

                //设置用户的名称和头像
                orderVo.setName(user.getName());
                orderVo.setImage(user.getImage());
                orderVo.setSenderId(user.getId().longValue());
            }

            //设置商品信息
            //2.1 查询商品是否存在
            ResponseResult responseResult = goodsClient.ProductById(orderVo.getGoodsId());
            if (responseResult.getCode()!=200){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"远程调用获取商品数据失败");
            }

            //拿取商品信息
            String jsonString = JSONUtil.toJsonStr(responseResult.getData());
            Product product = JSONUtil.toBean(jsonString, Product.class);

            //将图片路径转化为集合
            List<String> imageList = Arrays.stream(product.getImages().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());

            orderVo.setImages(imageList);
            orderVo.setPrice(product.getPrice());
            orderVo.setTitle(product.getTitle());

        }


        return ResponseResult.okResult(orderVos);
    }



    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult cancelOrder(Long id) {

        // 1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "取消订单参数为空");
        }

        // 2.查询订单
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "订单不存在");
        }

        // 3.检查订单状态
        if (!OrderStatus.UNPAID.equals(order.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单状态不允许取消");
        }

        // 4.更新订单状态为已取消
        order.setStatus(OrderStatus.CANCELLED_CLOSED);
        order.setUpdateTime(LocalDateTime.now());
        int updateResult = orderMapper.updateById(order);
        if (updateResult <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "订单取消失败");
        }

        // 5.恢复商品状态   重新上架商品
        // 5.更新商品状态
        ProductDto productDto=new ProductDto();

        productDto.setId(order.getGoodsId());
        productDto.setStatus(1);
        productDto.setUserId(order.getReceiverId());

        //远程调用商品上架
        ResponseResult responseResult1 = goodsClient.updateStatus(productDto);
        if (responseResult1.getCode()!=200){
            throw new RuntimeException("远程调用商品上架失败");
        }

        return ResponseResult.okResult("订单取消成功");
    }


    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteOrder(Long id) {

        // 1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "取消订单参数为空");
        }

        // 2.查询订单
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "订单不存在");
        }

        // 3.检查订单状态
        if (!OrderStatus.CANCELLED_CLOSED.equals(order.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单状态不允许删除");
        }

        //删除订单
        int i = orderMapper.deleteById(id);
        if (i <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"订单删除失败");
        }


        //删除订单详情
        LambdaQueryWrapper <OrderDetail> queryWrapper = new LambdaQueryWrapper <>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        int i1 = orderDetailMapper.delete(queryWrapper);
        if (i1 <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"订单详情删除失败");
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 支付
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult payOrder(Long id) {


        //1.参数判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"支付订单参数为空");
        }

        //2.查询订单是否存在
        Order order = orderMapper.selectById(id);

        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单不存在");
        }

        if (!OrderStatus.UNPAID.equals(order.getStatus())) {

            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误");
        }

        //模拟接入支付接口 假如支付成功


        //4.修改订单状态为已支付
        order.setPayTime(LocalDateTime.now());
        order.setStatus(OrderStatus.PAID_NOT_SHIPPED);

        int i = orderMapper.updateById(order);
        if (i <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"修改订单状态错误");
        }


        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 查询我的卖出
     *
     * @return
     */
    @Override
    public ResponseResult mySoldOrder(OrderFindDto orderFindDto) {



        //1.获取当前用户
        Integer userId = AppThreadLocalUtil.getUser().getId();

        LambdaQueryWrapper <Order>queryWrapper = new LambdaQueryWrapper<Order>();
        queryWrapper.eq(Order::getReceiverId, userId)
                .orderByDesc(Order::getCreateTime);
        ;

        //2.按照状态分类查询
        if (orderFindDto.getStatus()!=null){
            queryWrapper.eq(Order::getStatus,orderFindDto.getStatus());
        }


        //2.查询该用户卖出信息
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if (orders==null || orders.size()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"暂无卖出");
        }





        //最终返回结果

/*        @ApiModelProperty(value = "订单id")
        @TableId(value = "id", type = IdType.INPUT)
        private Long id;

        @ApiModelProperty(value = "总金额，单位为分")
        private Double totalFee;

        @ApiModelProperty(value = "支付类型，1、面交，2、邮寄")
        private Integer paymentType;

        private Long senderId;      // 发送者ID  商家id #

        private Long receiverId;    // 接收者ID  #

        @ApiModelProperty(value = "订单的状态，1、未付款 2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功 5、交易取消，订单关闭 6、交易结束，已评价")
        private Integer status;*/
        List<OrderVo> orderVos = BeanUtil.copyToList(orders, OrderVo.class);




        for (OrderVo orderVo : orderVos) {

            //设置用户信息

            //查询购买人的昵称和头像
            ResponseResult userInfo = userClient.getUserInfoById(orderVo.getSenderId());
            if (userInfo.getCode()==200){
                //拿取用户信息
                String jsonString = JSONUtil.toJsonStr(userInfo.getData());
                ApUser user = JSONUtil.toBean(jsonString, ApUser.class);

                //设置用户的名称和头像
                orderVo.setName(user.getName());
                orderVo.setImage(user.getImage());
                orderVo.setSenderId(user.getId().longValue());
            }

            //设置商品信息
            //2.1 查询商品是否存在
            ResponseResult responseResult = goodsClient.ProductById(orderVo.getGoodsId());
            if (responseResult.getCode()!=200){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"远程调用获取商品数据失败");
            }

            //拿取商品信息
            String jsonString = JSONUtil.toJsonStr(responseResult.getData());
            Product product = JSONUtil.toBean(jsonString, Product.class);

            //将图片路径转化为集合
            List<String> imageList = Arrays.stream(product.getImages().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());

            orderVo.setImages(imageList);
            orderVo.setPrice(product.getPrice());
            orderVo.setTitle(product.getTitle());

        }


        return ResponseResult.okResult(orderVos);

    }



    /**
     * 发货
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult shipOrder(Long id) {

        //1.参数判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"发货操作参数为空");
        }



        //2.查询订单是否存在
        Order order = orderMapper.selectById(id);

        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单不存在");
        }

        //订单必须是已付款 才可以发货
        if (!OrderStatus.PAID_NOT_SHIPPED.equals(order.getStatus())) {

            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误");
        }



        //4.修改订单状态为已发货
        order.setPayTime(LocalDateTime.now());
        order.setStatus(OrderStatus.SHIPPED_NOT_CONFIRMED);

        int i = orderMapper.updateById(order);
        if (i <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"修改订单状态错误");
        }


        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);

    }



    /**
     * 确认收货
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult confirmOrder(Long id) {


        //1.参数判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"发货操作参数为空");
        }



        //2.查询订单是否存在
        Order order = orderMapper.selectById(id);

        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单不存在");
        }

        //订单必须是已发货 才可以收获
        if (!OrderStatus.SHIPPED_NOT_CONFIRMED.equals(order.getStatus())) {

            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误");
        }



        //4.修改订单状态为已收获
        order.setPayTime(LocalDateTime.now());
        order.setStatus(OrderStatus.CONFIRMED_SUCCESS);

        int i = orderMapper.updateById(order);
        if (i <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"修改订单状态错误");
        }


        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 买家申请退款
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult refundOrder(Long id) {


        //1.id判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"申请退款id为空");
        }


        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单不存在");
        }

        // 检查订单状态是否允许退款
        if (!OrderStatus.PAID_NOT_SHIPPED.equals(order.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误,只有已付款未发货才可以退款");
        }


        // 更新订单状态为退款中
        order.setStatus(OrderStatus.REFUNDING);
        int updateCount = orderMapper.updateById(order);
        if (updateCount == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "更新订单状态失败");
        }

        // 返回成功结果
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 卖家同意退款
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult refundAgreeOrder(Long id) {

        //1.id判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"卖家同意退款id为空");
        }


        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单不存在");
        }

        // 检查订单状态是否允许退款
        if (!OrderStatus.REFUNDING.equals(order.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误,只有退款中才可以同意退款");
        }


        // 更新订单状态为已取消
        order.setStatus(OrderStatus.CANCELLED_CLOSED);
        int updateCount = orderMapper.updateById(order);
        if (updateCount == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "更新订单状态失败");
        }

        // 5.恢复商品状态   重新上架商品
        // 5.更新商品状态
        ProductDto productDto=new ProductDto();

        productDto.setId(order.getGoodsId());
        productDto.setStatus(1);
        productDto.setUserId(order.getReceiverId());

        //远程调用商品上架
        ResponseResult responseResult1 = goodsClient.updateStatus(productDto);
        if (responseResult1.getCode()!=200){
            throw new RuntimeException("远程调用商品上架失败");
        }

        // 返回成功结果
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 卖家拒绝退款
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult refundRejectOrder(Long id) {
        //1.id判空
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"卖家拒绝退款id为空");
        }


        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "订单不存在");
        }

        // 检查订单状态是否允许退款
        if (!OrderStatus.REFUNDING.equals(order.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"订单状态错误,只有退款中才可以拒绝退款");
        }


        // 更新订单状态为待发货
        order.setStatus(OrderStatus.PAID_NOT_SHIPPED);
        int updateCount = orderMapper.updateById(order);
        if (updateCount == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "更新订单状态失败");
        }

        // 返回成功结果
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}




































